﻿/*
创建人：Yuxj
日期：2023-04-23
描述：总体工时分配功能
*/
var page = {
    pagetotal: 0,
    pageSize: 5,
    pageNumber: 1,
    rootPath: getRootPath(), //网站根路径
    ajaxUrl: getRootPath() + "/Ashx/ZsHandler/WorkerStepTimeManageFormZS.ashx",
    //初始化页面
    init: function () {
        page.bind();
        customizedEasyuiPagination('pp'); //定制化分页
        page.addEditCell();
    },
    //页面事件绑定
    bind: function () {
        page.LoadDates();
        //人员工时统计详情
        $("#gdWorkHourData").datagrid({
            onLoadSuccess: function (data) {
                $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: page.pagetotal,
                    pageSize: page.pageSize,
                    pageNumber: page.pageNumber
                });
                NewcustomizedEasyuiPagination('pp'); //定制化分页
            },
            onClickRow: function (index, rowData) {
                page.reset(false, false, true);
                page.splitGridRecord();
            },
            columns: [[
                 { field: 'EMPLOYEEWORKTIMEZSID', title: 'EMPLOYEEWORKTIMEZSID', width: 150, align: 'center', hidden: true },
                 { field: 'FACTORYID', title: 'FACTORYID', width: 150, align: 'center', hidden: true },
                 { field: 'FULLNAME', title: '人员姓名', width: 120, align: 'center' },
		         { field: 'EMPLOYEENAME', title: '员工号', width: 150, align: 'center' },
                 { field: 'EMPLOYEEID', title: 'EMPLOYEEID', width: 150, align: 'center', hidden: true },
                 { field: 'WORKCENTERNAME', title: '工区', width: 150, align: 'center' },
                 { field: 'WORKCENTERNAMEID', title: 'WORKCENTERNAMEID', width: 150, align: 'center', hidden: true },
                 { field: 'SHIFTNAME', title: '班', width: 150, align: 'center' },
                 { field: 'SHIFTID', title: 'SHIFTID', width: 150, align: 'center', hidden: true },
                 { field: 'TEAMNAME', title: '组', width: 150, align: 'center' },
                 { field: 'TEAMID', title: 'TEAMID', width: 150, align: 'center', hidden: true },
		         { field: 'SUMWORKTIME', title: '原总工时', width: 120, align: 'center' },
                 { field: 'SPLITOUTTIME', title: '分出工时', width: 120, align: 'center' },
                 { field: 'SPLITINTIME', title: '分入工时', width: 120, align: 'center' },
                 { field: 'TOTALWORKTIME', title: '合计总工时', width: 120, align: 'center' },

	           ]]
        });

        //人员工时分配详情
        $("#gdWorkTimeSplitInfo").datagrid({
            onClickCell: function (index, field) {
                //编辑单元格
                if (page.endEditing('gdWorkTimeSplitInfo')) {
                    $('#gdWorkTimeSplitInfo').datagrid('editCell', { index: index, field: field });
                    page.editIndex = index;
                }
                //var e=arguments.callee.caller.caller.arguments[0]; 
                //console.log('onClickCell'); 
                return false;
            },
            columns: [[
            // { field: 'ck', title: '选择', checkbox: true },
                 {field: 'EMPLOYEEWORKTIMEZSID', title: 'EMPLOYEEWORKTIMEZSID', width: 150, align: 'center', hidden: true },
                 { field: 'EMPLOYEEID', title: 'EMPLOYEEID', width: 150, align: 'center', hidden: true },
                 { field: 'FULLNAME', title: '人员姓名', width: 120, align: 'center' },
		         { field: 'EMPLOYEENAME', title: '员工号', width: 150, align: 'center' },
                 { field: 'INWORKTIME', title: '本次分配工时', width: 120, align: 'center', editor: { type: 'numberbox', options: { precision: 2}} }

	           ]]
        });

        $("#gdSplitDetail").datagrid({
            columns: [[
                 { field: 'FROMFULLNAME', title: '分出人员', width: 120, align: 'center' },
                 { field: 'SPLITWORKTIME', title: '分出工时', width: 120, align: 'center', editor: { type: 'numberbox', options: { precision: 2}} },
                 { field: 'TOFULLNAME', title: '分入人员', width: 120, align: 'center' },

	           ]]
        });

        //查询按钮
        $('#btnSearch').on("click", function () {
            page.pageNumber = 1;
            page.searchData();
        });
        //分页事件
        $('#pp').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                customizedEasyuiPagination('pp'); //定制化分页
                page.pageSize = pageSize; page.pageNumber = pageNumber;
                page.searchData();
            }
        });
        //绑定分页go按钮
        $('#pageGo').on("click", function () {
            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            page.pageNumber = pageNumber;
            page.searchData();
        });
        //清除按钮
        $('#btnReset').on("click", function () {
            page.reset(true, true);
            page.pageNumber = 1; page.pagetotal = 0
            $('#pp').pagination('refresh', {
                total: page.pagetotal,
                pageSize: page.pageSize,
                pageNumber: page.pageNumber
            });
        });

        //工时分配按钮
        $('#btnSplit').on("click", function () {
            page.saveSplitWorkTimeData();
        });
        page.LoadFactory();
    },
    addEditCell: function () //给easyuigrid新增editcell方法
    {
        $.extend($.fn.datagrid.methods, {
            editCell: function (jq, param) {
                return jq.each(function () {
                    var opts = $(this).datagrid('options');
                    var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
                    for (var i = 0; i < fields.length; i++) {
                        var col = $(this).datagrid('getColumnOption', fields[i]);
                        col.editor1 = col.editor;
                        if (fields[i] != param.field) {
                            col.editor = null;
                        }
                    }
                    $(this).datagrid('beginEdit', param.index);
                    for (var i = 0; i < fields.length; i++) {
                        var col = $(this).datagrid('getColumnOption', fields[i]);
                        col.editor = col.editor1;
                    }
                });
            }
        });
    },
    endEditing: function (gridId) {
        if (page.editIndex == undefined) { return true }
        if ($('#' + gridId).datagrid('validateRow', page.editIndex)) {
            $('#' + gridId).datagrid('endEdit', page.editIndex);
            page.editIndex = undefined;
            return true;
        } else {
            return false;
        }
    },
    //工时拆分及验证
    saveSplitWorkTimeData: function (row) {
        clearMessage();
        var rowSelect = $("#gdWorkHourData").datagrid("getChecked");
        var rowDatas = $("#gdWorkTimeSplitInfo").datagrid("getRows");
        if (rowDatas.length == 0) {
            displayMessage("没有要分配的记录", false);
            return;
        }
        //工时总数判断 
        var totalworktime = parseFloat(rowSelect[0].TOTALWORKTIME);
        if (totalworktime <= 0) {
            displayMessage("该人员没有要分配的工时", false);
            return;
        }
        var employeeId = rowSelect[0].EMPLOYEEID;
        var sumworktime = 0;
        rowDatas.forEach(
            function (item) {
                sumworktime += parseFloat(item.INWORKTIME);
            }
        );

        if (totalworktime < sumworktime) {
            displayMessage("要分配的工时总数不能超过总工时！");
            return;
        }

        if (totalworktime > sumworktime) {
            displayMessage("分配的工时之和应等于总工时！");
            return;
        }

        var splitWorkTimeData = {
            action: "splitWorkTimeData",
            rowsData: JSON.stringify(rowDatas),
            beginDate: $("#txtStartDate").datebox('getValue'),
            endDate: $("#txtEndDate").datebox('getValue'),
            employeeId: employeeId

        }
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: splitWorkTimeData,
            cashe: false,
            async: true,
            beforeSend: function () {
                $('#gdWorkHourData').datagrid('loading');
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                var result = JSON.parse(data);
                if (result.Result) {
                    page.searchData();
                    displayMessage(result.Message, true);
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                alert(XMLHttpRequest.responseText);
            }
        });

    },
    //查询
    searchData: function () {
        clearEasyuiDataGrid("gdWorkTimeSplitInfo", 1);
        clearEasyuiDataGrid("gdSplitDetail", 1);
        var gridID = "#gdWorkHourData";
        var param = {
            action: "searchData",
            pageSize: page.pageSize,
            pageNumber: page.pageNumber,
            factoryId: $("#selfactory").combobox('getValue'),
            workcenterId: $("#selWorkCenter").combobox('getValue'),
            shiftId: $("#selShift").combobox('getValue'),
            //            shiftId: $("#selShift").hasClass('combo-f') ? $("#selShift").combobox('getValue') : $("#selShift").textbox('getValue'),根据控件类型判断是否有值
            teamId: $("#selTeam").combobox('getValue'),
            employeeName: $("#selFullName").combobox('getValue'),
            startDate: $("#txtStartDate").datebox('getValue'),
            endDate: $("#txtEndDate").datebox('getValue')
        };

        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
                $(gridID).datagrid('loading');
                $(this).attr("disabled", "disabled"); //禁用按钮
            },
            success: function (data) {
                //console.log(data);
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                var result = JSON.parse(data);
                if (result.Result) {
                    //给分页对象赋值
                    page.pagetotal = result.RowCount;
                    $(gridID).datagrid('loadData', { total: result.RowCount, rows: result.DBTable });
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $(gridID).datagrid('loaded');
                $(this).removeAttr("disabled"); //恢复按钮
                alert(XMLHttpRequest.responseText);
            }
        });
    },
    //点击行
    splitGridRecord: function () {
        var rowDatas = $("#gdWorkHourData").datagrid("getChecked");
        if (rowDatas.length == 0) {
            return;
        }

        page.loadSplitDetailRecord();

        var param = {
            action: "splitRecord",
            recordPara: JSON.stringify(rowDatas)
        };

        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                if (result.Result) {
                    var dt = result.DBTable;
                    //console.log(dt);
                    $("#gdWorkTimeSplitInfo").datagrid('loadData', { total: dt.length, rows: dt });
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#gdWorkTimeSplitInfo').datagrid('loaded');
                alert(XMLHttpRequest.responseText);
            }
        });
    },
    //点击行
    loadSplitDetailRecord: function () {
        var rowDatas = $("#gdWorkHourData").datagrid("getChecked");
        if (rowDatas.length == 0) {
            return;
        }
        //工时总数判断 
        var SPLITOUTTIME = parseFloat(rowDatas[0].SPLITOUTTIME);
        var SPLITINTIME = parseFloat(rowDatas[0].SPLITINTIME);
        if ((SPLITOUTTIME <= 0) && (SPLITINTIME <= 0)) {
            return;
        }

        var param = {
            action: "loadSplitDetailRecord",
            employeeID: rowDatas[0].EMPLOYEEID,
            beginDate: $("#txtStartDate").datebox('getValue'),
            endDate: $("#txtEndDate").datebox('getValue')
        };

        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                if (result.Result) {
                    var dt = result.DBTable;
                    $("#gdSplitDetail").datagrid('loadData', { total: dt.length, rows: dt });
                } else {
                    displayMessage(result.Message, false);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#gdSplitDetail').datagrid('loaded');
                alert(XMLHttpRequest.responseText);
            }
        });
    },

    //日期加载
    LoadDates: function () {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: { action: "loadDates" },
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                if (result != null) {
                    $('#txtStartDate').datebox('setValue', dayjs(result.DBTable[0]["begindate"]).format('YYYY-MM-DD'));
                    $('#txtEndDate').datebox('setValue', dayjs(result.DBTable[0]["enddate"]).format('YYYY-MM-DD'));
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },

    //分厂下拉初始化
    LoadFactory: function () {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: { action: "getFactory" },
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                $('#selfactory').combobox({
                    data: result,
                    valueField: 'FACTORYID',
                    textField: 'FACTORYNAME',
                    value: result[0].FACTORYID, //默认值
                    onSelect: function (record) {
                        if (record.FACTORYID !== "") {
                            page.bindWorkCenter(record.FACTORYID); //加载工区
                        }
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },
    //绑定工区
    bindWorkCenter: function (factoryid) {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: { action: "getWorkCenter", factoryId: factoryid },
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                $('#selWorkCenter').combobox({
                    data: result.DBTable,
                    valueField: 'WORKCENTERID',
                    textField: 'WORKCENTERNAME',
                    onSelect: function (record) {
                        if (record.WORKCENTERID !== "") {
                            page.bindShift(record.WORKCENTERID); //加载班组
                        }
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },
    //绑定组
    bindShift: function (workcenterid) {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: { action: "getShift", workcenterId: workcenterid },
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                $('#selShift').combobox({
                    data: result.DBTable,
                    valueField: 'SHIFTID',
                    textField: 'SHIFTNAME',
                    onSelect: function (record) {
                        if (record.SHIFTID !== "") {
                            page.bindTeam(record.SHIFTID); //加载班组
                            page.bindEmployee("", record.SHIFTID);
                        }
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },
    //绑定组
    bindTeam: function (shiftid) {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: { action: "getTeam", shiftId: shiftid, workCenterId: "" },
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                $('#selTeam').combobox({
                    data: result.DBTable,
                    valueField: 'TEAMID',
                    textField: 'TEAMNAME',
                    onSelect: function (record) {
                        if (record.TEAMID !== "") {
                            page.bindEmployee(record.TEAMID, shiftid); //加载班组
                        }
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },

    //绑定人员
    bindEmployee: function (teamid, shiftid) {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: { action: "getEmployee", teamId: teamid, shiftId: shiftid },
            cashe: false,
            async: true,
            beforeSend: function () {
            },
            success: function (data) {
                var result = JSON.parse(data);
                $('#selFullName').combobox({
                    data: result.DBTable,
                    valueField: 'EMPLOYEENAME',
                    textField: 'FULLNAME'
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        });
    },

    //清除方法，重要！！！
    reset: function (iscondition, isresult) {
        clearMessage();

    }
}
$(function () {
    page.init();
});